package com.qf.service;

import com.qf.entity.SysPermission;
import com.qf.entity.SysUser;
import com.qf.mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service
public class UserDetailServiceImpl implements UserDetailsService{
    @Autowired
    private SysUserMapper sysUserMapper;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser sysUser = sysUserMapper.loginByUsername(username);
        if (sysUser == null){
            throw new UsernameNotFoundException("用户不存在");
        }

        Set<String> authsSet = sysUserMapper.selectAuthsById(sysUser.getId());
        System.out.println("authsSet = " + authsSet);

        // 需要转换为 GrantedAuthority 类型
        Set<GrantedAuthority> auths = new HashSet<>();
        authsSet.forEach(auth->{
            auths.add(new SimpleGrantedAuthority(auth));
        });

        // 上面,只是查询出了权限,没有查询角色信息
        // 假设,查询出的角色是admin
        // 为了区分集合存储的是角色还是权限,要求角色以ROLE_开头
        auths.add(new SimpleGrantedAuthority("ROLE_超级管理员"));

        // 该方法返回的是 org.springframework.security.core.userdetails.User对象
        // 这个对象需要传入3个参数,用户名,密码,权限
        return new User(sysUser.getUsername(),sysUser.getPassword(),auths);
    }
}
